import { MicroAppNameEnum } from "@/utils/constants";
import { getVueInstance } from "@/main";
import path from "path";
import { DICT_TYPE, getDictValueByDictTypeAndLabel } from '@/utils/dict'

/**
 * qiankun微前端环境
 */
export function getQiankunEnv() {
  if (process.env.VUE_APP_QIANKUN_ENV === "true") {
    return true;
  }
  if (process.env.VUE_APP_QIANKUN_ENV === "false") {
    return false;
  }
  return process.env.VUE_APP_QIANKUN_ENV || false;
}

/**
 * qiankun微前端，获取当前展示的微应用
 * @param {*} currentPath 当前路径可选参数，不包含基础前缀/admin-ui/
 * @returns
 */
export function getCurrentMicroApp(currentPath) {
  const vueInstance = getVueInstance();
  const microAppNameObj = Object.values(MicroAppNameEnum).find((item) => {
    if (currentPath) {
      return currentPath.toLowerCase().startsWith(`/${item.name}`);
    }
    return (
      vueInstance?.$route?.path?.toLowerCase().startsWith(`/${item.name}`) ||
      window.location.pathname
        .toLowerCase()
        .startsWith(process.env.VUE_APP_APP_NAME + item.name)
    );
  });
  return microAppNameObj;
}

/**
 * 退出登录
 */
export async function toLogout() {
  const vueInstance = getVueInstance();
  vueInstance.$modal
    .confirm("确定注销并退出系统吗？", "提示")
    .then(() => {
      vueInstance.$store.dispatch("tagsView/delAllViews", []);
      vueInstance.$store.dispatch("LogOut").then(() => {
        vueInstance.$websocket.close();
        localStorage.clear();
        vueInstance.$router.replace({ name: "login" });
      });
    })
    .catch(() => {});
}

/**
 * 动态获取流程详情路由地址
 */
export function getProcessDetailPath() {
  let path = "/bpm/process-instance/detail";
  // qiankun微前端
  if (getQiankunEnv()) {
    const currentMicroApp = getCurrentMicroApp();
    if (currentMicroApp) {
      const name = currentMicroApp.name;
      // 菜单管理中的菜单路径，需要和此处保持一致，或者后期是否将跳转路径在菜单管理中动态配置
      path = `/${name}/task/my/detail`;
    }
  }
  return path;
}

/**
 * 动态获取主页url
 */
export function getHomepagePath() {
  let homepagePath = "/";
  // qiankun微前端，动态设置主页url
  if (getQiankunEnv()) {
    homepagePath = getMicroAppFirstMenuPath(MicroAppNameEnum.DATA_SHARE_PORTAL.name) || process.env.VUE_APP_NEW_HOME_URL
  }
  return homepagePath;
}

/**
 * 获取子应用第一个菜单path
 * @returns
 */
export function getMicroAppFirstMenuPath(
  currentMicroAppName = getCurrentMicroApp()?.name
) {
  if (!currentMicroAppName) {
    return "";
  }
  const vueInstance = getVueInstance();
  const originSiderRouters =
    vueInstance?.$store?.state?.permission?.sidebarRouters;
  if (!originSiderRouters || originSiderRouters.length === 0) {
    return "";
  }
  // 先过滤出第三方菜单，其中，共享交换门户由于不在侧边栏展示，默认隐藏，所以单独处理
  const thirdPartyRouters = originSiderRouters.filter(
    (item) =>
      (!item.hidden && item.meta && item.meta["thirdMenu"]) ||
      item.path === `/${MicroAppNameEnum.DATA_SHARE_PORTAL.name}`
  );
  // 当前应用的根路由列表
  const currentMicroAppRouters = thirdPartyRouters.filter(
    (item) => item.path === `/${currentMicroAppName}`
  );
  if (
    !currentMicroAppRouters ||
    currentMicroAppRouters.length === 0 ||
    !currentMicroAppRouters[0].children ||
    currentMicroAppRouters[0].children.length === 0
  ) {
    return "";
  }

  let result = "";
  const getFirstChild = (item, tempPath) => {
    if (!item) {
      return;
    }
    const targetPath = path.resolve(tempPath, item.path);
    if (item.children && item.children.length > 0) {
      getFirstChild(item.children[0], targetPath);
    } else {
      result = targetPath;
    }
  };
  // 获取第一个叶子菜单path
  getFirstChild(
    currentMicroAppRouters[0].children[0],
    currentMicroAppRouters[0].path
  );
  return result;
}

/**
 * 获取共享交换门户标题名称
 * @returns 
 */
export async function getExchangePortalTitle() {
  const label = 'exchange_portal_title'
  return await getDictValueByDictTypeAndLabel(DICT_TYPE.EXCHANGE_PORTAL_PROFILE, label) || MicroAppNameEnum.DATA_SHARE_PORTAL.desc
}

/**
 * 获取共享交换门户logo
 * @returns 
 */
export async function getExchangePortalLogo() {
  const label = 'exchange_portal_logo'
  return await getDictValueByDictTypeAndLabel(DICT_TYPE.EXCHANGE_PORTAL_PROFILE, label) || require(`@/assets/images/${MicroAppNameEnum.DATA_SHARE_PORTAL.log}`)
}

/**
 * 获取共享交换门户背景图
 * @returns 
 */
export function getExchangePortalBackground() {
  const label = 'exchange_portal_background'
  return getDictValueByDictTypeAndLabel(DICT_TYPE.EXCHANGE_PORTAL_PROFILE, label)
}
